<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>监控统计 - Bou Scheduler</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.7.2/font/bootstrap-icons.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="/">
                <i class="bi bi-clock-history"></i> Bou Scheduler
            </a>
            <div class="collapse navbar-collapse">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/tasks">任务管理</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/monitor">监控统计</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/settings">系统设置</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <!-- 主要内容 -->
    <div class="container mt-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1><i class="bi bi-graph-up"></i> 监控统计</h1>
            <div class="btn-group" role="group">
                <button type="button" class="btn btn-outline-primary btn-sm" onclick="refreshData()">
                    <i class="bi bi-arrow-clockwise"></i> 刷新数据
                </button>
                <button type="button" class="btn btn-outline-warning btn-sm" onclick="cleanupCompletedTasks()">
                    <i class="bi bi-trash"></i> 清理已完成任务
                </button>
                <button type="button" class="btn btn-outline-info btn-sm" onclick="resetStatistics()">
                    <i class="bi bi-arrow-clockwise"></i> 重置统计信息
                </button>
                <button type="button" class="btn btn-outline-success btn-sm" onclick="exportData()">
                    <i class="bi bi-download"></i> 导出数据
                </button>
            </div>
        </div>
        
        <!-- 实时统计 -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card text-center bg-primary text-white">
                    <div class="card-body">
                        <h3 id="totalTasks">0</h3>
                        <p class="mb-0">总任务数</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center bg-warning text-white">
                    <div class="card-body">
                        <h3 id="pendingTasks">0</h3>
                        <p class="mb-0">待执行任务</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center bg-info text-white">
                    <div class="card-body">
                        <h3 id="runningTasks">0</h3>
                        <p class="mb-0">执行中任务</p>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card text-center bg-success text-white">
                    <div class="card-body">
                        <h3 id="successTasks">0</h3>
                        <p class="mb-0">成功任务</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 性能指标 -->
        <div class="row mb-4">
            <div class="col-md-4">
                <div class="card text-center bg-info text-white">
                    <div class="card-body">
                        <h4 id="tasksPerSecond">0</h4>
                        <p class="mb-0">任务/秒</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card text-center bg-success text-white">
                    <div class="card-body">
                        <h4 id="successRate">0%</h4>
                        <p class="mb-0">成功率</p>
                    </div>
                </div>
            </div>
            <div class="col-md-4">
                <div class="card text-center bg-warning text-white">
                    <div class="card-body">
                        <h4 id="uptime">0秒</h4>
                        <p class="mb-0">运行时长</p>
                    </div>
                </div>
            </div>
        </div>

        <!-- 图表区域 -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="bi bi-pie-chart"></i> 任务状态分布</h5>
                    </div>
                    <div class="card-body">
                        <canvas id="statusChart" width="400" height="300"></canvas>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="bi bi-bar-chart"></i> 任务类型分布</h5>
                    </div>
                    <div class="card-body">
                        <canvas id="typeChart" width="400" height="300"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- 执行时间趋势 -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="bi bi-graph-up"></i> 任务执行趋势 (最近24小时)</h5>
                    </div>
                    <div class="card-body">
                        <canvas id="trendChart" width="800" height="300"></canvas>
                    </div>
                </div>
            </div>
        </div>

        <!-- 系统状态 -->
        <div class="row mb-4">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="bi bi-cpu"></i> 系统状态</h5>
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span>调度器状态:</span>
                            <span id="schedulerStatus" class="badge bg-secondary">未知</span>
                        </div>
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span>Redis连接:</span>
                            <span id="redisStatus" class="badge bg-secondary">未知</span>
                        </div>
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span>时间轮状态:</span>
                            <span id="timeWheelStatus" class="badge bg-secondary">未知</span>
                        </div>
                        <div class="d-flex justify-content-between align-items-center">
                            <span>最后更新:</span>
                            <span id="lastUpdate" class="text-muted">-</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="bi bi-gear"></i> 系统配置</h5>
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span>时间轮大小:</span>
                            <span id="wheelSize" class="text-muted">-</span>
                        </div>
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span>时间轮刻度:</span>
                            <span id="tickDuration" class="text-muted">-</span>
                        </div>
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <span>线程池大小:</span>
                            <span id="threadPoolSize" class="text-muted">-</span>
                        </div>
                        <div class="d-flex justify-content-between align-items-center">
                            <span>队列容量:</span>
                            <span id="queueCapacity" class="text-muted">-</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js"></script>
    <script src="/js/utils.js"></script>
    <script>
        let statusChart, typeChart, trendChart;
        let updateInterval;

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeCharts();
            loadData();
            
            // 每30秒自动刷新数据
            updateInterval = setInterval(loadData, 30000);
        });

        // 初始化图表
        function initializeCharts() {
            // 任务状态分布饼图
            const statusCtx = document.getElementById('statusChart').getContext('2d');
            statusChart = new Chart(statusCtx, {
                type: 'pie',
                data: {
                    labels: ['待执行', '执行中', '成功', '失败', '已取消'],
                    datasets: [{
                        data: [0, 0, 0, 0, 0],
                        backgroundColor: [
                            '#ffc107', '#17a2b8', '#28a745', '#dc3545', '#6c757d'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });

            // 任务类型分布柱状图
            const typeCtx = document.getElementById('typeChart').getContext('2d');
            typeChart = new Chart(typeCtx, {
                type: 'bar',
                data: {
                    labels: ['邮件', '短信', '通知', '数据处理', '报告生成', '自定义'],
                    datasets: [{
                        label: '任务数量',
                        data: [0, 0, 0, 0, 0, 0],
                        backgroundColor: '#007bff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });

            // 执行趋势折线图
            const trendCtx = document.getElementById('trendChart').getContext('2d');
            trendChart = new Chart(trendCtx, {
                type: 'line',
                data: {
                    labels: [],
                    datasets: [{
                        label: '成功任务',
                        data: [],
                        borderColor: '#28a745',
                        backgroundColor: 'rgba(40, 167, 69, 0.1)',
                        tension: 0.4
                    }, {
                        label: '失败任务',
                        data: [],
                        borderColor: '#dc3545',
                        backgroundColor: 'rgba(220, 53, 69, 0.1)',
                        tension: 0.4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });
        }

        // 加载数据
        function loadData() {
            Promise.all([
                fetch('/api/tasks').then(r => r.json()),
                fetch('/api/tasks/statistics').then(r => r.json()),
                fetch('/api/tasks/scheduler/status').then(r => r.json())
            ]).then(([tasksData, statsData, schedulerData]) => {
                if (tasksData.success) {
                    updateTaskStats(tasksData.data);
                    updateCharts(tasksData.data);
                }
                
                if (statsData.success) {
                    updatePerformanceStats(statsData.data);
                }
                
                if (schedulerData.success) {
                    updateSystemStatus(schedulerData.data);
                }
                
                updateLastUpdateTime();
            }).catch(error => {
                console.error('Error loading data:', error);
                showError('数据加载失败，请检查网络连接');
            });
        }

        // 更新任务统计
        function updateTaskStats(tasks) {
            document.getElementById('totalTasks').textContent = tasks.length;
            document.getElementById('pendingTasks').textContent = tasks.filter(t => t.status === 'PENDING').length;
            document.getElementById('runningTasks').textContent = tasks.filter(t => t.status === 'RUNNING').length;
            document.getElementById('successTasks').textContent = tasks.filter(t => t.status === 'SUCCESS').length;
        }

        // 更新性能统计
        function updatePerformanceStats(stats) {
            document.getElementById('tasksPerSecond').textContent = (stats.tasksPerSecond || 0).toFixed(2);
            
            // 成功率已经是百分比值（0-100），直接显示，不需要再乘以100
            const successRate = stats.successRate || 0;
            document.getElementById('successRate').textContent = successRate.toFixed(1) + '%';
            
            document.getElementById('uptime').textContent = formatDuration(stats.uptime || 0);
            
            // 添加调试日志
            console.log('性能统计更新:', {
                tasksPerSecond: stats.tasksPerSecond,
                successRate: stats.successRate,
                uptime: stats.uptime,
                rawSuccessRate: successRate
            });
        }

        // 更新系统状态
        function updateSystemStatus(status) {
            const schedulerStatus = document.getElementById('schedulerStatus');
            if (status === 'RUNNING') {
                schedulerStatus.className = 'badge bg-success';
                schedulerStatus.textContent = '运行中';
            } else {
                schedulerStatus.className = 'badge bg-danger';
                schedulerStatus.textContent = '已停止';
            }
            
            // 模拟其他状态
            document.getElementById('redisStatus').className = 'badge bg-success';
            document.getElementById('redisStatus').textContent = '正常';
            
            document.getElementById('timeWheelStatus').className = 'badge bg-success';
            document.getElementById('timeWheelStatus').textContent = '正常';
        }

        // 更新图表
        function updateCharts(tasks) {
            // 更新状态分布图
            const statusCounts = {
                'PENDING': 0, 'RUNNING': 0, 'SUCCESS': 0, 'FAILED': 0, 'CANCELLED': 0
            };
            
            tasks.forEach(task => {
                statusCounts[task.status] = (statusCounts[task.status] || 0) + 1;
            });
            
            statusChart.data.datasets[0].data = [
                statusCounts['PENDING'],
                statusCounts['RUNNING'],
                statusCounts['SUCCESS'],
                statusCounts['FAILED'],
                statusCounts['CANCELLED']
            ];
            statusChart.update();

            // 更新类型分布图
            const typeCounts = {};
            tasks.forEach(task => {
                typeCounts[task.taskType] = (typeCounts[task.taskType] || 0) + 1;
            });
            
            const typeLabels = ['EMAIL', 'SMS', 'NOTIFICATION', 'DATA_PROCESSING', 'REPORT_GENERATION', 'CUSTOM'];
            const typeData = typeLabels.map(type => typeCounts[type] || 0);
            
            typeChart.data.datasets[0].data = typeData;
            typeChart.update();

            // 更新趋势图
            updateTrendChart(tasks);
        }

        // 更新趋势图
        function updateTrendChart(tasks) {
            // 生成最近24小时的时间标签
            const labels = [];
            const successData = [];
            const failedData = [];
            
            const now = new Date();
            for (let i = 23; i >= 0; i--) {
                const time = new Date(now.getTime() - i * 60 * 60 * 1000);
                labels.push(time.getHours() + ':00');
                
                // 统计该小时的任务数量
                const hourStart = new Date(time.getFullYear(), time.getMonth(), time.getDate(), time.getHours());
                const hourEnd = new Date(hourStart.getTime() + 60 * 60 * 1000);
                
                const hourTasks = tasks.filter(task => {
                    const completeTime = new Date(task.completeTime);
                    return completeTime >= hourStart && completeTime < hourEnd;
                });
                
                successData.push(hourTasks.filter(t => t.status === 'SUCCESS').length);
                failedData.push(hourTasks.filter(t => t.status === 'FAILED').length);
            }
            
            trendChart.data.labels = labels;
            trendChart.data.datasets[0].data = successData;
            trendChart.data.datasets[1].data = failedData;
            trendChart.update();
        }

        // 更新最后更新时间
        function updateLastUpdateTime() {
            const now = new Date();
            document.getElementById('lastUpdate').textContent = now.toLocaleString('zh-CN');
        }

        // 刷新数据
        function refreshData() {
            loadData();
            showSuccess('数据已刷新');
        }

        // 导出数据
        function exportData() {
            fetch('/api/tasks')
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const csvContent = convertToCSV(data.data);
                    downloadFile(csvContent, 'task-statistics.csv', 'text/csv');
                    showSuccess('数据导出成功');
                } else {
                    showError('导出失败: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error exporting data:', error);
                showError('导出失败，请检查网络连接');
            });
        }

        // 转换为CSV格式
        function convertToCSV(tasks) {
            const headers = ['任务ID', '任务名称', '任务类型', '状态', '优先级', '创建时间', '执行时间', '完成时间'];
            const rows = tasks.map(task => [
                task.taskId,
                task.taskName,
                task.taskType,
                task.status,
                task.priority,
                task.createTime,
                task.executeTime,
                task.completeTime
            ]);
            
            return [headers, ...rows].map(row => 
                row.map(field => `"${field || ''}"`).join(',')
            ).join('\n');
        }

        // 格式化持续时间
        function formatDuration(milliseconds) {
            if (!milliseconds || milliseconds < 0) return '0秒';
            
            const seconds = Math.floor(milliseconds / 1000);
            const minutes = Math.floor(seconds / 60);
            const hours = Math.floor(minutes / 60);
            const days = Math.floor(hours / 24);

            if (days > 0) return `${days}天 ${hours % 24}小时 ${minutes % 60}分钟`;
            if (hours > 0) return `${hours}小时 ${minutes % 60}分钟`;
            if (minutes > 0) return `${minutes}分钟 ${seconds % 60}秒`;
            return `${seconds}秒`;
        }

        // 获取优先级徽章
        function getPriorityBadge(priority) {
            const priorityMap = {
                0: { class: 'bg-primary', text: '普通' },
                1: { class: 'bg-warning', text: '高' },
                2: { class: 'bg-danger', text: '紧急' },
                3: { class: 'bg-secondary', text: '低' }
            };
            const priorityInfo = priorityMap[priority] || { class: 'bg-secondary', text: '未知' };
            return `<span class="badge ${priorityInfo.class}">${priorityInfo.text}</span>`;
        }

        // 清理已完成任务
        function cleanupCompletedTasks() {
            // 使用通用清理函数，清理1小时前的任务
            if (typeof window.globalCleanupCompletedTasks === 'function') {
                window.globalCleanupCompletedTasks(1, function(data) {
                    // 成功回调：重新加载数据以更新统计
                    loadData();
                }, function(errorMessage) {
                    // 错误回调：可以在这里添加额外的错误处理
                    console.error('清理任务失败:', errorMessage);
                });
            } else {
                // 如果通用函数不可用，使用备用实现
                cleanupCompletedTasksLocal();
            }
        }

        // 本地清理任务实现（避免递归调用）
        function cleanupCompletedTasksLocal() {
            if (confirm('确定要清理所有已完成任务吗？这将删除所有已完成的任务记录。')) {
                // 设置清理时间为1小时前，使用本地时间
                const now = new Date();
                const oneHourAgo = new Date(now.getTime() - 60 * 60 * 1000);
                
                // 格式化为 YYYY-MM-DDTHH:mm:ss 格式，使用本地时间
                const year = oneHourAgo.getFullYear();
                const month = String(oneHourAgo.getMonth() + 1).padStart(2, '0');
                const day = String(oneHourAgo.getDate()).padStart(2, '0');
                const hours = String(oneHourAgo.getHours()).padStart(2, '0');
                const minutes = String(oneHourAgo.getMinutes()).padStart(2, '0');
                const seconds = String(oneHourAgo.getSeconds()).padStart(2, '0');
                
                const beforeTime = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
                
                console.log('清理时间参数:', {
                    now: now.toLocaleString('zh-CN'),
                    oneHourAgo: oneHourAgo.toLocaleString('zh-CN'),
                    beforeTime: beforeTime
                });
                
                fetch(`/api/tasks/cleanup?beforeTime=${beforeTime}`, {
                    method: 'POST'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showSuccess(`已完成任务已清理，共清理 ${data.data} 个任务`);
                        loadData(); // 重新加载数据以更新统计
                    } else {
                        showError('清理失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error cleaning up completed tasks:', error);
                    showError('清理失败，请检查网络连接');
                });
            }
        }

        // 重置统计信息
        function resetStatistics() {
            if (confirm('确定要重置所有统计信息吗？这将清除所有性能指标和任务状态。')) {
                fetch('/api/tasks/scheduler/statistics/reset', {
                    method: 'POST'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showSuccess('统计信息已重置');
                        loadData(); // 重新加载数据以更新统计
                    } else {
                        showError('重置失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error resetting statistics:', error);
                    showError('重置失败，请检查网络连接');
                });
            }
        }

        // 页面卸载时清理定时器
        window.addEventListener('beforeunload', function() {
            if (updateInterval) {
                clearInterval(updateInterval);
            }
        });
    </script>
</body>
</html>
